
\section {下载与安装} \label{download_install}

❂你可以使用我们提供的二进制包,或者源代码,安装 TensorFlow.

%
%%
\subsection {安装需求}

❂TensorFlow Python API 目前支持 Python 2.7 和 python 3.3以上版本。

❂支持 GPU 运算的版本 (仅限Linux) 需要 Cuda Toolkit 7.0 和 CUDNN 6.5 V2. 具体请参考\href{ref????}{Cuda安装}。

%
%%
\subsection {安装总述}
TensorFlow 支持通过以下不同的方式安装：
\begin{itemize}
%✠% \item \hyperref[pip_install]{Pip 安装}: Install TensorFlow on your machine, possibly upgrading previously installed Python packages. May impact existing Python programs on your machine.
%✠% \item \hyperref[virtualenv_install]{Virtualenv 安装}: Install TensorFlow in its own directory, not impacting any existing Python programs on your machine.
%✠% \item \hyperref[docker_install]{Docker 安装}: Run TensorFlow in a Docker container isolated from all other programs on your machine.

\item \hyperref[pip_install]{Pip 安装}: 在你的机器上安装TensorFlow，可能会同时更新之前安装的Python包，并且影响到你机器当前可运行的Python程序．

\item \hyperref[virtualenv_install]{Virtualenv 安装}: 在一个独立的路径下安装TensorFlow，不会影响到你机器当前运行的Python程序．

\item \hyperref[docker_install]{Docker 安装}: 在一个独立的Docker容器中安装TensorFlow，并且不会影响到你机器上的任何其他程序．
\end{itemize}

%✠% If you are familiar with Pip, Virtualenv, or Docker, please feel free to adapt the instructions to your particular needs. The names of the pip and Docker images are listed in the corresponding installation sections.

%✠% If you encounter installation errors, see common problems for some solutions.

❂ 如果你已经很熟悉Pip、Virtualenv、Docker这些工具的使用，请利用教程中提供的代码，根据你的需求安装TensorFlow。你会在下文的对应的安装教程中找到Pip或Docker安装所需的镜像。

❂ 如果你遇到了安装错误，请参考章节\hyperref[comm_prob]{常见问题}寻找解决方案。

%
%%
%✠%\subsection {Pip Installatioin} \label{pip_install}
\subsection {Pip 安装} \label{pip_install}

%✠% \href{https://en.wikipedia.org/wiki/Pip_(package_manager)}{Pip} is a package management system used to install and manage software packages written in Python.

❂ \href{https://en.wikipedia.org/wiki/Pip_(package_manager)}{Pip} 是一个用于安装和管理Python软件包的管理系统。

%✠% The packages that will be installed or upgraded during the pip install are listed in the \href{https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/pip_package/setup.py}{REQUIRED\_PACKAGES section of setup.py}

%✠% The packages that will be installed or upgraded during the pip install are listed in the \href{https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/pip_package/setup.py}{REQUIRED\_PACKAGES section of setup.py}

❂ 安装依赖包(\href{https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/pip_package/setup.py}{REQUIRED\_PACKAGES section of setup.py}) 列出了pip安装时将会被安装或更新的库文件。

%✠% Install pip (or pip3 for python3) if it is not already installed:

❂ 如果pip尚未被安装，请使用以下代码先安装pip(如果你使用的是Python 3请安装 pip3 ):

\begin{lstlisting}[language = bash]
# Ubuntu/Linux 64-bit
$ sudo apt-get install python-pip python-dev
\end{lstlisting}

\begin{lstlisting}
# Mac OS X
$ sudo easy_install pip
\end{lstlisting}

%✠% Install TensorFlow:
❂ 安装 TensorFlow:

\begin{lstlisting}
# Ubuntu/Linux 64-bit, CPU only:
$ sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.6.0-cp27-none-linux_x86_64.whl
\end{lstlisting}

\begin{lstlisting}
# Ubuntu/Linux 64-bit, GPU enabled:
$ sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.6.0-cp27-none-linux_x86_64.whl
\end{lstlisting}

\begin{lstlisting}[language = bash]
# Mac OS X, CPU only:
$ sudo easy_install --upgrade six
$ sudo pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.6.0-py2-none-any.whl
\end{lstlisting}

%✠% For Python 3:
❂ 基于 Python 3 的 TensorFlow 安装:

\begin{lstlisting}
# Ubuntu/Linux 64-bit, CPU only:
$ sudo pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.6.0-cp34-none-linux_x86_64.whl
\end{lstlisting}

\begin{lstlisting}
# Ubuntu/Linux 64-bit, GPU enabled:
$ sudo pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.6.0-cp34-none-linux_x86_64.whl

\end{lstlisting}

\begin{lstlisting}[language = bash]
# Mac OS X, CPU only:
$ sudo easy_install --upgrade six
$ sudo pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.6.0-py3-none-any.whl
\end{lstlisting}

%✠% You can now test your \hyperref[test_install]{installation}.
❂ 至此你可以\hyperref[test_install]{测试安装}是否成功。

%
%%
%✠% \subsection {Virtualenv Installation} \label{virtualenv_install}
❂ \subsection {基于 Virtualenv 安装} \label{virtualenv_install}

\href{http://docs.python-guide.org/en/latest/dev/virtualenvs/}{Virtualenv} is a tool to keep the dependencies required by different Python projects in separate places. The Virtualenv installation of TensorFlow will not override pre-existing version of the Python packages needed by TensorFlow.

%✠% With \href{https://pypi.python.org/pypi/virtualenv}{Virtualenv} the installation is as follows:

❂ 基于\href{https://pypi.python.org/pypi/virtualenv}{Virtualenv}的安装分为以下几步:

\begin{itemize}
%✠% \item Install pip and Virtualenv.
%✠% \item Create a Virtualenv environment.
%✠% \item Activate the Virtualenv environment and install TensorFlow in it.
%✠% \item After the install you will activate the Virtualenv environment each time you want to use TensorFlow.
\item 安装 pip 和 Virtualenv.
\item 建立一个 Virtualenv 环境.
\item 激活该 Virtualenv 环境，并且在该环境下安装 TensorFlow.
\item 安装完成之后，每次你需要使用TensorFlow之前必须激活这个Virtualenv 环境.
\end{itemize}

%✠% Install pip and Virtualenv:
❂ 安装 pip 和 Virtualenv:

\begin{lstlisting}
# Ubuntu/Linux 64-bit
$ sudo apt-get install python-pip python-dev python-virtualenv
\end{lstlisting}

\begin{lstlisting}
# Mac OS X
$ sudo easy_install pip
$ sudo pip install --upgrade virtualenv
\end{lstlisting}

%✠% Create a Virtualenv environment in the directory \lstinline{~/tensorflow}:
❂ 在\lstinline{~/tensorflow}路径下建立一个 Virtualenv 环境:

\begin{lstlisting}
$ virtualenv --system-site-packages ~/tensorflow
\end{lstlisting}

Activate the environment and use pip to install TensorFlow inside it:
\begin{lstlisting}
$ source ~/tensorflow/bin/activate  # If using bash
$ source ~/tensorflow/bin/activate.csh  # If using csh
(tensorflow)$  # Your prompt should change

# Ubuntu/Linux 64-bit, CPU only:
(tensorflow)$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

# Ubuntu/Linux 64-bit, GPU enabled:
(tensorflow)$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

# Mac OS X, CPU only:
(tensorflow)$ pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
\end{lstlisting}

and again for python3:

\begin{lstlisting}
$ source ~/tensorflow/bin/activate  # If using bash
$ source ~/tensorflow/bin/activate.csh  # If using csh
(tensorflow)$  # Your prompt should change

# Ubuntu/Linux 64-bit, CPU only:
(tensorflow)$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.6.0-cp34-none-linux_x86_64.whl

# Ubuntu/Linux 64-bit, GPU enabled:
(tensorflow)$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.6.0-cp34-none-linux_x86_64.whl

# Mac OS X, CPU only:
(tensorflow)$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.6.0-py3-none-any.whl
\end{lstlisting}

With the Virtualenv environment activated, you can now \hyperref[test_install]{test your installation}.

When you are done using TensorFlow, deactivate the environment.

\begin{lstlisting}
(tensorflow)$ deactivate
$  # Your prompt should change back
\end{lstlisting}

To use TensorFlow later you will have to activate the Virtualenv environment again:
\begin{lstlisting}
$ source ~/tensorflow/bin/activate  # If using bash.
$ source ~/tensorflow/bin/activate.csh  # If using csh.
(tensorflow)$  # Your prompt should change.
# Run Python programs that use TensorFlow.
...
# When you are done using TensorFlow, deactivate the environment.
(tensorflow)$ deactivate
\end{lstlisting}

%
%%
\subsection {Docker Installation} \label{docker_install}
\href{http://docker.com/}{Docker} is a system to build self contained versions of a Linux operating system running on your machine. When you install and run TensorFlow via Docker it completely isolates the installation from pre-existing packages on your machine.

We provide 4 Docker images:

\begin{itemize}
\item \lstinline{b.gcr.io/tensorflow/tensorflow}: TensorFlow CPU binary image.
\item \lstinline{b.gcr.io/tensorflow/tensorflow:latest-devel}:CPU Binary image plus source code.
\item \lstinline{b.gcr.io/tensorflow/tensorflow:latest-gpu}:TensorFlow GPU binary image.
\item \lstinline{b.gcr.io/tensorflow/tensorflow:latest-devel-gpu}:GPU Binary image plus source code.
\end{itemize}

We also have tags with latest replaced by a released version (eg \lstinline{0.6.0-gpu}).

With Docker the installation is as follows:

\begin{itemize}
\item Install Docker on your machine.
\item Create a \href{http://docs.docker.com/engine/installation/ubuntulinux/#create-a-docker-group}{Docker group} to allow launching containers without sudo.
\item Launch a Docker container with the TensorFlow image. The image gets downloaded automatically on first launch.
\end{itemize}

See \href{http://docs.docker.com/engine/installation/}{installing Docker} for instructions on installing Docker on your machine.

After Docker is installed, launch a Docker container with the TensorFlow binary image as follows.

\begin{lstlisting}
$ docker run -it b.gcr.io/tensorflow/tensorflow
\end{lstlisting}

If you're using a container with GPU support, some additional flags must be passed to expose the GPU device to the container. For the default config, we include a \href{https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/docker/docker_run_gpu.sh}{script} in the repo with these flags, so the command-line would look like:

\begin{lstlisting}
$ path/to/repo/tensorflow/tools/docker/docker_run_gpu.sh b.gcr.io/tensorflow/tensorflow:gpu
\end{lstlisting}

You can now \hyperref[test_install]{test your installation} within the Docker container.

% ✠ % ❂ % ✠ % ❂ % ✠ % ❂ % ✠ % ❂ % ✠ % ❂ % ✠ % ❂ % ✠ % ❂ % ✠ % ❂

%
%%
%✠% \subsection {Test the TensorFlow Installation} \label{test_install}
❂ \subsection {测试 TensorFlow 安装} \label{test_install}

%%%
\subsubsection {(Optional, Linux) Enable GPU Support}

If you installed the GPU version of TensorFlow, you must also install the Cuda Toolkit~7.0 and CUDNN~6.5~V2. Please see \hyperref[install_cuda]{Cuda installation}.

You also need to set the \lstinline{LD_LIBRARY_PATH} and \lstinline{CUDA_HOME} environment variables. Consider adding the commands below to your \lstinline{~/.bash_profile}. These assume your CUDA installation is in \lstinline{/usr/local/cuda}:

\begin{lstlisting}
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/cuda/lib64"
export CUDA_HOME=/usr/local/cuda
\end{lstlisting}

%%%
\subsubsection {Run TensorFlow from the Command Line}

See \hyperref[comm_prob]{common problems} if an error happens.

Open a terminal and type the following:

\begin{lstlisting}
$ python
...
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
>>> print(sess.run(hello))
Hello, TensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> print(sess.run(a + b))
42
>>>
\end{lstlisting}

%%%
\subsubsection {Run a TensorFlow demo model}

All TensorFlow packages, including the demo models, are installed in the Python library. The exact location of the Python library depends on your system, but is usually one of:
\begin{lstlisting}
/usr/local/lib/python2.7/dist-packages/tensorflow
/usr/local/lib/python2.7/site-packages/tensorflow
\end{lstlisting}

You can find out the directory with the following command:
\begin{lstlisting}
$ python -c 'import site; print("\n".join(site.getsitepackages()))'
\end{lstlisting}

The simple demo model for classifying handwritten digits from the MNIST dataset is in the sub-directory \lstinline{models/image/mnist/convolutional.py}. You can run it from the command line as follows:
\begin{lstlisting}
# Using 'python -m' to find the program in the python search path:
$ python -m tensorflow.models.image.mnist.convolutional
Extracting data/train-images-idx3-ubyte.gz
Extracting data/train-labels-idx1-ubyte.gz
Extracting data/t10k-images-idx3-ubyte.gz
Extracting data/t10k-labels-idx1-ubyte.gz
...etc...

# You can alternatively pass the path to the model program file to the python interpreter.
$ python /usr/local/lib/python2.7/dist-packages/tensorflow/models/image/mnist/convolutional.py
...
\end{lstlisting}


%
%%
\subsection {Installing from source}
When installing from source you will build a pip wheel that you then install using pip. You'll need pip for that, so install it as described \hyperref[pip_install]{above}.

%%%
\subsubsection {Clone the TensorFlow repository}
\begin{lstlisting}
$ git clone --recurse-submodules https://github.com/tensorflow/tensorflow
\end{lstlisting}
\lstinline{--recurse-submodules} is required to fetch the protobuf library that TensorFlow depends on.


%%%
\subsubsection {Installation for Linux}

\paragraph{Install Bazel}

Follow instructions here to install the dependencies for Bazel. Then download bazel version 0.1.1 using the installer for your system and run the installer as mentioned there:

\begin{lstlisting}
$ chmod +x PATH_TO_INSTALL.SH
$ ./PATH_TO_INSTALL.SH --user
\end{lstlisting}

Remember to replace \lstinline{PATH_TO_INSTALL.SH} with the location where you downloaded the installer.

Finally, follow the instructions in that script to place bazel into your binary path.

\paragraph{Install other dependencies}

\begin{lstlisting}
$ sudo apt-get install python-numpy swig python-dev
\end{lstlisting}

\paragraph{Configure the installation}

Run the configure script at the root of the tree. The configure script asks you for the path to your python interpreter and allows (optional) configuration of the CUDA libraries (see \hyperref[install_cuda]{below}).

This step is used to locate the python and numpy header files.

\begin{lstlisting}
$ ./configure
Please specify the location of python. [Default is /usr/bin/python]:
\end{lstlisting}

\paragraph{Optional: Install CUDA (GPUs on Linux)} \label{install_cuda}

In order to build or run TensorFlow with GPU support, both Cuda Toolkit 7.0 and CUDNN 6.5 V2 from NVIDIA need to be installed.

TensorFlow GPU support requires having a GPU card with NVidia Compute Capability >= 3.5. Supported cards include but are not limited to:

\begin{itemize}
\item NVidia Titan
\item NVidia Titan X
\item NVidia K20
\item NVidia K40
\end{itemize}

Download and install Cuda Toolkit 7.0

https://developer.nvidia.com/cuda-toolkit-70

Install the toolkit into e.g. /usr/local/cuda

Download and install CUDNN Toolkit 6.5

https://developer.nvidia.com/rdp/cudnn-archive

Uncompress and copy the cudnn files into the toolkit directory. Assuming the toolkit is installed in /usr/local/cuda:

\begin{lstlisting}
tar xvzf cudnn-6.5-linux-x64-v2.tgz
sudo cp cudnn-6.5-linux-x64-v2/cudnn.h /usr/local/cuda/include
sudo cp cudnn-6.5-linux-x64-v2/libcudnn* /usr/local/cuda/lib64
\end{lstlisting}

Configure TensorFlow's canonical view of Cuda libraries

When running the configure script from the root of your source tree, select the option Y when asked to build TensorFlow with GPU support.

\begin{lstlisting}
$ ./configure
Please specify the location of python. [Default is /usr/bin/python]:
Do you wish to build TensorFlow with GPU support? [y/N] y
GPU support will be enabled for TensorFlow

Please specify the location where CUDA 7.0 toolkit is installed. Refer to
README.md for more details. [default is: /usr/local/cuda]: /usr/local/cuda

Please specify the location where CUDNN 6.5 V2 library is installed. Refer to
README.md for more details. [default is: /usr/local/cuda]: /usr/local/cuda

Setting up Cuda include
Setting up Cuda lib64
Setting up Cuda bin
Setting up Cuda nvvm
Configuration finished
\end{lstlisting}

This creates a canonical set of symbolic links to the Cuda libraries on your system. Every time you change the Cuda library paths you need to run this step again before you invoke the bazel build command.

Build your target with GPU support

From the root of your source tree, run:

\begin{lstlisting}
$ bazel build -c opt --config=cuda //tensorflow/cc:tutorials_example_trainer

$ bazel-bin/tensorflow/cc/tutorials_example_trainer --use_gpu
# Lots of output. This tutorial iteratively calculates the major eigenvalue of
# a 2x2 matrix, on GPU. The last few lines look like this.
000009/000005 lambda = 2.000000 x = [0.894427 -0.447214] y = [1.788854 -0.894427]
000006/000001 lambda = 2.000000 x = [0.894427 -0.447214] y = [1.788854 -0.894427]
000009/000009 lambda = 2.000000 x = [0.894427 -0.447214] y = [1.788854 -0.894427]
\end{lstlisting}

Note that "--config=cuda" is needed to enable the GPU support.

Enabling Cuda 3.0

TensorFlow officially supports Cuda devices with 3.5 and 5.2 compute capabilities. In order to enable earlier Cuda devices such as Grid K520, you need to target Cuda 3.0. This can be done through TensorFlow unofficial settings with "configure".

\begin{lstlisting}
$ TF_UNOFFICIAL_SETTING=1 ./configure

# Same as the official settings above

WARNING: You are configuring unofficial settings in TensorFlow. Because some
external libraries are not backward compatible, these settings are largely
untested and unsupported.

Please specify a list of comma-separated Cuda compute capabilities you want to
build with. You can find the compute capability of your device at:
https://developer.nvidia.com/cuda-gpus.
Please note that each additional compute capability significantly increases
your build time and binary size. [Default is: "3.5,5.2"]: 3.0

Setting up Cuda include
Setting up Cuda lib64
Setting up Cuda bin
Setting up Cuda nvvm
Configuration finished
\end{lstlisting}

Known issues

Although it is possible to build both Cuda and non-Cuda configs under the same source tree, we recommend to run "bazel clean" when switching between these two configs in the same source tree.

You have to run configure before running bazel build. Otherwise, the build will fail with a clear error message. In the future, we might consider making this more conveninent by including the configure step in our build process, given necessary bazel new feature support.


%%%
\subsubsection {Installation for Mac OS X}

We recommend using \href{http://brew.sh/}{homebrew} to install the bazel and SWIG dependencies, and installing python dependencies using easy_install or pip.

\paragraph{Dependencies}

Follow instructions here to install the dependencies for Bazel. You can then use homebrew to install bazel and SWIG:

\begin{lstlisting}
$ brew install bazel swig
\end{lstlisting}

You can install the python dependencies using easy_install or pip. Using easy_install, run

\begin{lstlisting}
$ sudo easy_install -U six
$ sudo easy_install -U numpy
$ sudo easy_install wheel
\end{lstlisting}

We also recommend the \href{https://ipython.org/}{ipython} enhanced python shell, so best install that too:

\begin{lstlisting}
$ sudo easy_install ipython
\end{lstlisting}

\paragraph{Configure the installation}

Run the \lstinline{configure} script at the root of the tree. The configure script asks you for the path to your python interpreter.

This step is used to locate the python and numpy header files.

\begin{lstlisting}
$ ./configure
Please specify the location of python. [Default is /usr/bin/python]:
Do you wish to build TensorFlow with GPU support? [y/N]
\end{lstlisting}

%%%
\subsubsection {Create the pip package and install}

\begin{lstlisting}
$ bazel build -c opt //tensorflow/tools/pip_package:build_pip_package

# To build with GPU support:
$ bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package

$ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

# The name of the .whl file will depend on your platform.
$ pip install /tmp/tensorflow_pkg/tensorflow-0.5.0-cp27-none-linux_x86_64.whl
\end{lstlisting}

%
%%
\subsection {Train your first TensorFlow neural net model}

Starting from the root of your source tree, run:

\begin{lstlisting}
$ cd tensorflow/models/image/mnist
$ python convolutional.py
Succesfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Succesfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Succesfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Succesfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting data/train-images-idx3-ubyte.gz
Extracting data/train-labels-idx1-ubyte.gz
Extracting data/t10k-images-idx3-ubyte.gz
Extracting data/t10k-labels-idx1-ubyte.gz
Initialized!
Epoch 0.00
Minibatch loss: 12.054, learning rate: 0.010000
Minibatch error: 90.6%
Validation error: 84.6%
Epoch 0.12
Minibatch loss: 3.285, learning rate: 0.010000
Minibatch error: 6.2%
Validation error: 7.0%
...
...
\end{lstlisting}


%
%%

% \subsection {Common Problems} \label{comm_prob}
\subsection {常见问题} \label{comm_prob}

%%%
\subsubsection {GPU-related issues}

If you encounter the following when trying to run a TensorFlow program:

\begin{lstlisting}
ImportError: libcudart.so.7.0: cannot open shared object file: No such file or directory
\end{lstlisting}

Make sure you followed the the GPU installation \hyperref[install_cuda]{instructions}.

%%%
\subsubsection {Pip installation issues}

\paragraph{Can't find setup.py}

If, during pip install, you encounter an error like:

\begin{lstlisting}
...
IOError: [Errno 2] No such file or directory: '/tmp/pip-o6Tpui-build/setup.py'
\end{lstlisting}

Solution: upgrade your version of pip:

\begin{lstlisting}
pip install --upgrade pip
\end{lstlisting}

This may require sudo, depending on how pip is installed.

\paragraph{SSLError: SSL\_VERIFY\_FAILED}

If, during pip install from a URL, you encounter an error like:

\begin{lstlisting}
...
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
\end{lstlisting}

Solution: Download the wheel manually via curl or wget, and pip install locally.

%%%
\subsubsection {Linux issues}

If you encounter:

\begin{lstlisting}
...
 "__add__", "__radd__",
             ^
SyntaxError: invalid syntax
\end{lstlisting}

Solution: make sure you are using Python 2.7.

%%%
\subsubsection {Mac OS X: ImportError: No module named copyreg}

On Mac OS X, you may encounter the following when importing tensorflow.

\begin{lstlisting}
>>> import tensorflow as tf
...
ImportError: No module named copyreg
\end{lstlisting}

Solution: TensorFlow depends on protobuf, which requires the Python package \lstinline{six-1.10.0}. Apple's default Python installation only provides \lstinline{six-1.4.1}.

You can resolve the issue in one of the following ways:
\begin{itemize}
\item pgrade the Python installation with the current version of \lstinline{six}:
\begin{lstlisting}
$ sudo easy_install -U six
\end{lstlisting}

\item Install TensorFlow with a separate Python library:
  \begin{itemize}
  \item Virtualenv
  \item Docker
  \end{itemize}
Install a separate copy of Python via Homebrew or MacPorts and re-install TensorFlow in that copy of Python.
\end{itemize}




%%%
\subsubsection {Mac OS X: TypeError: \lstinline{__init__()} got an unexpected keyword argument 'syntax'}

On Mac OS X, you may encounter the following when importing tensorflow.

\begin{lstlisting}
>>> import tensorflow as tf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 4, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 13, in <module>
    from tensorflow.core.framework.graph_pb2 import *
...
  File "/usr/local/lib/python2.7/site-packages/tensorflow/core/framework/tensor_shape_pb2.py", line 22, in <module>
    serialized_pb=_b('\n,tensorflow/core/framework/tensor_shape.proto\x12\ntensorflow\"d\n\x10TensorShapeProto\x12-\n\x03\x64im\x18\x02 \x03(\x0b\x32 .tensorflow.TensorShapeProto.Dim\x1a!\n\x03\x44im\x12\x0c\n\x04size\x18\x01 \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\tb\x06proto3')
TypeError: __init__() got an unexpected keyword argument 'syntax'
\end{lstlisting}

This is due to a conflict between protobuf versions (we require protobuf 3.0.0). The best current solution is to make sure older versions of protobuf are not installed, such as:

\begin{lstlisting}
$ pip install --upgrade protobuf
\end{lstlisting}



%%%% ## 二进制安装 <a class="md-anchor" id="AUTOGENERATED-binary-installation"></a>

%%%% TensorFlow Python API 依赖 Python 2.7 版本.

%%%% 在 Linux 和 Mac 下最简单的安装方式, 是使用 [pip](https://pypi.python.org/pypi/pip)
%%%% 安装.

%%%% 如果在安装过程中遇到错误, 请查阅 [常见问题](#common_install_problems).
%%%% 为了简化安装步骤, 建议使用 virtualenv, 教程见 [这里](#virtualenv_install).

%%%% ### Ubuntu/Linux <a class="md-anchor" id="AUTOGENERATED-ubuntu-linux"></a>

%%%% ```bash
%%%% # 仅使用 CPU 的版本
%%%% $ pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

%%%% # 开启 GPU 支持的版本 (安装该版本的前提是已经安装了 CUDA sdk)
%%%% $ pip install https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl
%%%% ```

%%%% ### Mac OS X <a class="md-anchor" id="AUTOGENERATED-mac-os-x"></a>

%%%% 在 OS X 系统上, 我们推荐先安装 [homebrew](http://brew.sh), 然后执行
%%%% `brew install python`, 以便能够使用 homebrew 中的 Python 安装
%%%% TensorFlow. 另外一种推荐的方式是在 [virtualenv](#virtualenv_install)
%%%% 中安装 TensorFlow.

%%%% ```bash
%%%% # 当前版本只支持 CPU
%%%% $ pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
%%%% ```

%%%% ## 基于 Docker 的安装 <a class="md-anchor" id="AUTOGENERATED-docker-based-installation"></a>

%%%% 我们也支持通过 [Docker](http://docker.com/) 运行 TensorFlow.
%%%% 该方式的优点是不用操心软件依赖问题.

%%%% 首先, [安装 Docker](http://docs.docker.com/engine/installation/). 一旦 Docker
%%%% 已经启动运行, 可以通过命令启动一个容器:

%%%% ```bash
%%%% $ docker run -it b.gcr.io/tensorflow/tensorflow
%%%% ```

%%%% 该命令将启动一个已经安装好 TensorFlow 及相关依赖的容器.

%%%% ### 其它镜像 <a class="md-anchor" id="AUTOGENERATED-additional-images"></a>

%%%% 默认的 Docker 镜像只包含启动和运行 TensorFlow 所需依赖库的一个最小集. 我们额外提供了
%%%% 下面的容器, 该容器同样可以通过上述 `docker run` 命令安装:

%%%% * `b.gcr.io/tensorflow/tensorflow-full`: 镜像中的 TensorFlow 是从源代码完整安装的,
  %%%% 包含了编译和运行 TensorFlow 所需的全部工具. 在该镜像上, 可以直接使用源代码进行实验,
  %%%% 而不需要再安装上述的任何依赖.
 %%%%
%%%% ## 基于 VirtualEnv 的安装 <a class="md-anchor" id="virtualenv_install"></a>

%%%% 我们推荐使用 [virtualenv](https://pypi.python.org/pypi/virtualenv) 创建一个隔离的容器, 来安装 TensorFlow. 这是可选的, 但是这样做能使排查安装问题变得更容易.

%%%% 首先, 安装所有必备工具:

%%%% ```bash
%%%% # 在 Linux 上:
%%%% $ sudo apt-get install python-pip python-dev python-virtualenv

%%%% # 在 Mac 上:
%%%% $ sudo easy_install pip  # 如果还没有安装 pip
%%%% $ sudo pip install --upgrade virtualenv
%%%% ```

%%%% 接下来, 建立一个全新的 virtualenv 环境. 为了将环境建在 `~/tensorflow`
%%%% 目录下, 执行:

%%%% ```bash
%%%% $ virtualenv --system-site-packages ~/tensorflow
%%%% $ cd ~/tensorflow
%%%% ```

%%%% 然后, 激活 virtualenv:

%%%% ```bash
%%%% $ source bin/activate  # 如果使用 bash
%%%% $ source bin/activate.csh  # 如果使用 csh
%%%% (tensorflow)$  # 终端提示符应该发生变化
%%%% ```

%%%% 在 virtualenv 内, 安装 TensorFlow:

%%%% ```bash
%%%% (tensorflow)$ pip install --upgrade <$url_to_binary.whl>
%%%% ```

%%%% 接下来, 使用类似命令运行 TensorFlow 程序:

%%%% ```bash
%%%% (tensorflow)$ cd tensorflow/models/image/mnist
%%%% (tensorflow)$ python convolutional.py

%%%% # 当使用完 TensorFlow
%%%% (tensorflow)$ deactivate  # 停用 virtualenv

%%%% $  # 你的命令提示符会恢复原样
%%%% ```

%%%% ## 尝试你的第一个 TensorFlow 程序 <a class="md-anchor" id="AUTOGENERATED-try-your-first-tensorflow-program"></a>

%%%% ### (可选) 启用 GPU 支持 <a class="md-anchor" id="AUTOGENERATED--optional--enable-gpu-support"></a>

%%%% 如果你使用 pip 二进制包安装了开启 GPU 支持的 TensorFlow, 你必须确保
%%%% 系统里安装了正确的 CUDA sdk 和 CUDNN 版本. 请参间  [CUDA 安装教程](#install_cuda)

%%%% 你还需要设置 `LD_LIBRARY_PATH` 和 `CUDA_HOME` 环境变量. 可以考虑将下面的命令
%%%% 添加到 `~/.bash_profile` 文件中, 这样每次登陆后自动生效. 注意, 下面的命令
%%%% 假定 CUDA 安装目录为 `/usr/local/cuda`:

%%%% ```bash
%%%% export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/cuda/lib64"
%%%% export CUDA_HOME=/usr/local/cuda
%%%% ```

%%%% ### 运行 TensorFlow <a class="md-anchor" id="AUTOGENERATED-run-tensorflow"></a>

%%%% 打开一个 python 终端:

%%%% ```bash
%%%% $ python

%%%% >>> import tensorflow as tf
%%%% >>> hello = tf.constant('Hello, TensorFlow!')
%%%% >>> sess = tf.Session()
%%%% >>> print sess.run(hello)
%%%% Hello, TensorFlow!
%%%% >>> a = tf.constant(10)
%%%% >>> b = tf.constant(32)
%%%% >>> print sess.run(a+b)
%%%% 42
%%%% >>>

%%%% ```

%%%% ## 从源码安装 <a class="md-anchor" id="source"></a>

%%%% ### 克隆 TensorFlow 仓库 <a class="md-anchor" id="AUTOGENERATED-clone-the-tensorflow-repository"></a>

%%%% ```bash
%%%% $ git clone --recurse-submodules https://github.com/tensorflow/tensorflow
%%%% ```

%%%% `--recurse-submodules` 参数是必须得, 用于获取 TesorFlow 依赖的 protobuf 库.

%%%% ### Linux 安装 <a class="md-anchor" id="AUTOGENERATED-installation-for-linux"></a>

%%%% #### 安装 Bazel <a class="md-anchor" id="AUTOGENERATED-install-bazel"></a>

%%%% 首先依照 [教程](http://bazel.io/docs/install.html) 安装 Bazel 的依赖.
%%%% 然后使用下列命令下载和编译 Bazel 的源码:

%%%% ```bash
%%%% $ git clone https://github.com/bazelbuild/bazel.git
%%%% $ cd bazel
%%%% $ git checkout tags/0.1.0
%%%% $ ./compile.sh
%%%% ```

%%%% 上面命令中拉取的代码标签为 `0.1.0`, 兼容 Tensorflow 目前版本. bazel 的`HEAD` 版本 (即最新版本) 在这里可能不稳定.

%%%% 将执行路径 `output/bazel` 添加到 `$PATH` 环境变量中.

%%%% #### 安装其他依赖 <a class="md-anchor" id="AUTOGENERATED-install-other-dependencies"></a>

%%%% ```bash
%%%% $ sudo apt-get install python-numpy swig python-dev
%%%% ```

%%%% #### 可选: 安装 CUDA (在 Linux 上开启 GPU 支持) <a class="md-anchor" id="install_cuda"></a>

%%%% 为了编译并运行能够使用 GPU 的 TensorFlow, 需要先安装 NVIDIA 提供的 Cuda Toolkit 7.0
%%%% 和 CUDNN 6.5 V2.

%%%% TensorFlow 的 GPU 特性只支持 NVidia Compute Capability >= 3.5 的显卡. 被支持的显卡
%%%% 包括但不限于:

%%%% * NVidia Titan
%%%% * NVidia Titan X
%%%% * NVidia K20
%%%% * NVidia K40

%%%% ##### 下载并安装 Cuda Toolkit 7.0 <a class="md-anchor" id="AUTOGENERATED-download-and-install-cuda-toolkit-7.0"></a>

%%%% [下载地址](https://developer.nvidia.com/cuda-toolkit-70)

%%%% 将工具安装到诸如 `/usr/local/cuda` 之类的路径.

%%%% ##### 下载并安装 CUDNN Toolkit 6.5 <a class="md-anchor" id="AUTOGENERATED-download-and-install-cudnn-toolkit-6.5"></a>

%%%% [下载地址](https://developer.nvidia.com/rdp/cudnn-archive)

%%%% 解压并拷贝 CUDNN 文件到 Cuda Toolkit 7.0 安装路径下. 假设 Cuda Toolkit 7.0 安装
%%%% 在 `/usr/local/cuda`, 执行以下命令:

%%%% ``` bash
%%%% tar xvzf cudnn-6.5-linux-x64-v2.tgz
%%%% sudo cp cudnn-6.5-linux-x64-v2/cudnn.h /usr/local/cuda/include
%%%% sudo cp cudnn-6.5-linux-x64-v2/libcudnn* /usr/local/cuda/lib64
%%%% ```

%%%% ##### 配置 TensorFlow 的 Cuba 选项 <a class="md-anchor" id="AUTOGENERATED-configure-tensorflow-s-canonical-view-of-cuda-libraries"></a>

%%%% 从源码树的根路径执行:

%%%% ``` bash
%%%% $ ./configure
%%%% Do you wish to bulid TensorFlow with GPU support? [y/n] y
%%%% GPU support will be enabled for TensorFlow

%%%% Please specify the location where CUDA 7.0 toolkit is installed. Refer to
%%%% README.md for more details. [default is: /usr/local/cuda]: /usr/local/cuda

%%%% Please specify the location where CUDNN 6.5 V2 library is installed. Refer to
%%%% README.md for more details. [default is: /usr/local/cuda]: /usr/local/cuda

%%%% Setting up Cuda include
%%%% Setting up Cuda lib64
%%%% Setting up Cuda bin
%%%% Setting up Cuda nvvm
%%%% Configuration finished
%%%% ```

%%%% 这些配置将建立到系统 Cuda 库的符号链接. 每当 Cuda 库的路径发生变更时, 必须重新执行上述
%%%% 步骤, 否则无法调用 bazel 编译命令.

%%%% ##### 编译目标程序, 开启 GPU 支持 <a class="md-anchor" id="AUTOGENERATED-build-your-target-with-gpu-support."></a>

%%%% 从源码树的根路径执行:

%%%% ```bash
%%%% $ bazel build -c opt --config=cuda //tensorflow/cc:tutorials_example_trainer

%%%% $ bazel-bin/tensorflow/cc/tutorials_example_trainer --use_gpu
%%%% # 大量的输出信息. 这个例子用 GPU 迭代计算一个 2x2 矩阵的主特征值 (major eigenvalue).
%%%% # 最后几行输出和下面的信息类似.
%%%% 000009/000005 lambda = 2.000000 x = [0.894427 -0.447214] y = [1.788854 -0.894427]
%%%% 000006/000001 lambda = 2.000000 x = [0.894427 -0.447214] y = [1.788854 -0.894427]
%%%% 000009/000009 lambda = 2.000000 x = [0.894427 -0.447214] y = [1.788854 -0.894427]
%%%% ```

%%%% 注意, GPU 支持需通过编译选项 "--config=cuda" 开启.

%%%% ##### 已知问题 <a class="md-anchor" id="AUTOGENERATED-known-issues"></a>

%%%% * 尽管可以在同一个源码树下编译开启 Cuda 支持和禁用 Cuda 支持的版本, 我们还是推荐在
%%%% 在切换这两种不同的编译配置时, 使用 "bazel clean" 清理环境.

%%%% * 在执行 bazel 编译前必须先运行 configure, 否则编译会失败并提示错误信息. 未来,
%%%% 我们可能考虑将 configure 步骤包含在编译过程中, 以简化整个过程, 前提是 bazel 能够提供新的特性支持这样.

%%%% ### Mac OS X 安装 <a class="md-anchor" id="AUTOGENERATED-installation-for-mac-os-x"></a>

%%%% Mac 和 Linux 需要的软件依赖完全一样, 但是安装过程区别很大. 以下链接用于帮助你
%%%% 在 Mac OS X 上安装这些依赖:

%%%% #### Bazel <a class="md-anchor" id="AUTOGENERATED-bazel"></a>

%%%% 参见[本网页](http://bazel.io/docs/install.html)的 Mac OS X 安装指南.

%%%% #### SWIG <a class="md-anchor" id="AUTOGENERATED-swig"></a>

%%%% [Mac OS X 安装教程](http://www.swig.org/Doc3.0/Preface.html#Preface_osx_installation).

%%%% 注意: 你需要安装[PCRE](ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/),
%%%% 而*不是* PCRE2.

%%%% #### Numpy <a class="md-anchor" id="AUTOGENERATED-numpy"></a>

%%%% 参见[安装教程](http://docs.scipy.org/doc/numpy/user/install.html).

%%%% ### 创建 pip 包并安装 <a class="md-anchor" id="create-pip"></a>

%%%% ```bash
%%%% $ bazel build -c opt //tensorflow/tools/pip_package:build_pip_package

%%%% $ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

%%%% # .whl 文件的实际名字与你所使用的平台有关
%%%% $ pip install /tmp/tensorflow_pkg/tensorflow-0.5.0-cp27-none-linux_x86_64.whl
%%%% ```

%%%% ## 训练你的第一个 TensorFlow 神经网络模型 <a class="md-anchor" id="AUTOGENERATED-train-your-first-tensorflow-neural-net-model"></a>

%%%% 从源代码树的根路径执行:

%%%% ```python
%%%% $ cd tensorflow/models/image/mnist
%%%% $ python convolutional.py
%%%% Succesfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
%%%% Succesfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
%%%% Succesfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
%%%% Succesfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
%%%% Extracting data/train-images-idx3-ubyte.gz
%%%% Extracting data/train-labels-idx1-ubyte.gz
%%%% Extracting data/t10k-images-idx3-ubyte.gz
%%%% Extracting data/t10k-labels-idx1-ubyte.gz
%%%% Initialized!
%%%% Epoch 0.00
%%%% Minibatch loss: 12.054, learning rate: 0.010000
%%%% Minibatch error: 90.6%
%%%% Validation error: 84.6%
%%%% Epoch 0.12
%%%% Minibatch loss: 3.285, learning rate: 0.010000
%%%% Minibatch error: 6.2%
%%%% Validation error: 7.0%
%%%% ...
%%%% ...
%%%% ```

%%%% ## 常见问题 <a class="md-anchor" id="common_install_problems"></a>

%%%% ### GPU 相关问题 <a class="md-anchor" id="AUTOGENERATED-gpu-related-issues"></a>

%%%% 如果在尝试运行一个 TensorFlow 程序时出现以下错误:

%%%% ```python
%%%% ImportError: libcudart.so.7.0: cannot open shared object file: No such file or directory
%%%% ```

%%%% 请确认你正确安装了 GPU 支持, 参见 [相关章节](#install_cuda).

%%%% ### 在 Linux 上 <a class="md-anchor" id="AUTOGENERATED-on-linux"></a>

%%%% 如果出现错误:

%%%% ```python
%%%% ...
 %%%% "__add__", "__radd__",
             %%%% ^
%%%% SyntaxError: invalid syntax
%%%% ```

%%%% 解决方案: 确认正在使用的 Python 版本为 Python 2.7.

%%%% ### 在 Mac OS X 上 <a class="md-anchor" id="AUTOGENERATED-on-macosx"></a>

%%%% 如果出现错误:

%%%% ```python
%%%% import six.moves.copyreg as copyreg

%%%% ImportError: No module named copyreg
%%%% ```

%%%% 解决方案: TensorFlow 使用的 protobuf 依赖 `six-1.10.0`. 但是, Apple 的默认 python 环境
%%%% 已经安装了 `six-1.4.1`, 该版本可能很难升级. 这里提供几种方法来解决该问题:

%%%% 1. 升级全系统的 `six`:

    %%%% ```bash
    %%%% sudo easy_install -U six
    %%%% ```

%%%% 2. 通过 homebrew 安装一个隔离的 python 副本:

    %%%% ```bash
    %%%% brew install python
    %%%% ```

%%%% 3. 在[`virtualenv`](#virtualenv_install) 内编译或使用 TensorFlow.
%%%%

%%%% 如果出现错误:

%%%% ```
%%%% >>> import tensorflow as tf
%%%% Traceback (most recent call last):
  %%%% File "<stdin>", line 1, in <module>
  %%%% File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 4, in <module>
    %%%% from tensorflow.python import *
  %%%% File "/usr/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 13, in <module>
    %%%% from tensorflow.core.framework.graph_pb2 import *
%%%% ...
  %%%% File "/usr/local/lib/python2.7/site-packages/tensorflow/core/framework/tensor_shape_pb2.py", line 22, in <module>
    %%%% serialized_pb=_b('\n,tensorflow/core/framework/tensor_shape.proto\x12\ntensorflow\"d\n\x10TensorShapeProto\x12-\n\x03\x64im\x18\x02 \x03(\x0b\x32 .tensorflow.TensorShapeProto.Dim\x1a!\n\x03\x44im\x12\x0c\n\x04size\x18\x01 \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\tb\x06proto3')
%%%% TypeError: __init__() got an unexpected keyword argument 'syntax'
%%%% ```

%%%% 这是由于安装了冲突的 protobuf 版本引起的, TensorFlow 需要的是 protobuf 3.0.0. 当前
%%%% 最好的解决方案是确保没有安装旧版本的 protobuf, 可以使用以下命令重新安装 protobuf 来解决
%%%% 冲突:

%%%% ```bash
%%%% brew reinstall --devel protobuf
%%%% ```

%%%% > 原文：[Download and Setup](http://tensorflow.org/get_started/os_setup.md)  翻译：[@doc001](https://github.com/PFZheng)  校对：[@yangtze](https://github.com/sstruct)
